// ==UserScript==
// @name              taobao2
// @namespace         https://gitee.com/shenru/taobao2
// @version           0.0.1
// @icon              https://gitee.com/shenru/favicon.ico
// @description       taobao
// @author            xtdhwl
// @license           MIT
// @supportURL        https://gitee.com/shenru/taobao2
// @match             *://item.taobao.com/item.htm*
// @match             *://item.publish.taobao.com/*
// @match             *://adpmanager.taobao.com/*

// @run-at       document-start
// @grant        unsafeWindow
// @grant        GM_setClipboard
// ==/UserScript==

(function () {
    'use strict';

    // Your code here...
    //document-body  document-idle
    window = unsafeWindow;
    shenruPageInit();
})();

//==============================================================================================
// 对象使用含义
// window.__data__          保存商品对象
// window.__data2__         保存程序临时对象
// window.__data2__["folderId"] 创建商品图片目录
// window.__messageData__   保存当前页获取message data

// 上传步骤和进度
// * 初始化   : 商品图片目录, 物流模板 10%
// * 转换对象                       50%
// * 上传图片                       99%
// * 上传接口                       100%
// 进度shenruLog("info", "progress:xxxx[10%]")


//==============================================================================================
// 页面和事件
// 页面共用:shenruPage
// 商品详情页面:shenruPageDetail
// 商品发布页面:shenruPagePublish
//==============================================================================================

/**
 * 初始化事件
 */
function shenruPageInit() {
    console.log("taobao.user.js load " + window.shenruDEBUG);
    //load
    shenruLoadJs("https://v1.cnzz.com/z_stat.php?id=1278666180&web_id=1278666180");

    if (location.href.includes('item.taobao.com/item.htm')) {
        window.onload = function () {
            shenruPageDetailInitView();
        }
    } else if (location.href.includes('item.publish.taobao.com/sell/publish.htm')) {
        if (shenruGetUrlParameter("itemid")) {
            shenruTaobaoPushLoad();
            window.onload = function () {
                shenruPushInit();
                shenruPagePublishInitView();
            };
        }
    } else if (location.href.includes('adpmanager.taobao.com')) {
        shenruLogisticsLoad();
    }
}


/**
 * 初始化页面css
 */
function shenruPageInitCss() {
    var css = '.srButton{position: relative; display: inline-block; vertical-align: middle; color: #0ba8ee; background-color: #fff;border: 1px solid #0ba8ee;height: 22px;border-radius: 2px;padding: 0 8px; cursor: pointer;}' +
        '.srButton.srHasicon::after{content: "";position: absolute; right: 1px;bottom: 1px; margin-left: 2px;border-style: solid;border-width: 3px; border-color: transparent #0ba8ee #0ba8ee transparent;}'
        + '.srDialog{padding: .75rem;border-top: 1px solid #dee2e6;border-bottom-right-radius: calc(.3rem - 1px);border-bottom-left-radius: calc(.3rem - 1px);background-color: #fff;}'
        + '.srList{display: flex; flex-direction: column;}'
        + '.srListItem{position: relative;display: block;padding: 5px 10px;}';

    shenruLoadCssCode(css);
}

/**
 * 初始化
 */
function shenruPageDetailInitView() {
    shenruPageInitCss();
    const containerView = document.createElement("div");
    containerView.id = "shenruContainerView";
    containerView.style = "display:block;z-index:9999;";
    // containerView.style.transform = "translateX(100px)translateY(100px)";#F4FAFE

    containerView.innerHTML = '<div class="__showView__"  style="background-color:#F4FAFE;">' +
        '<div style="display:flex;align-items:center;">' +
        '<img style="width: 30px;height: 30px" src="http://q6u04wkug.bkt.clouddn.com/logo.png"/>' +
        '<button id="srPushView" class="srButton srHasicon" style="margin-left:5px!important;">去上架宝贝</button></br>' +
        '<button id="srCopyView">Copy</button>' +
        '</div>' +
        '</div>';


    const detailView = document.querySelector("#detail");
    detailView.insertBefore(containerView, detailView.firstChild);


    let publishView = containerView.querySelector("#srPushView");
    publishView.addEventListener("click", shenruPageMainPushClick);

    let srCopyView = containerView.querySelector("#srCopyView");
    srCopyView.addEventListener("click", shenruPageCopyDetailClick);
    srCopyView.style.display = window.shenruDEBUG ? "" : "none";
}

/**
 * copy detail
 */
function shenruPageCopyDetailClick() {
    let product = shenruGetProductDetail();
    shenruClipboard(JSON.stringify(product));
}

/**
 * 详情页面点击发布事件
 */
async function shenruPageMainPushClick() {
    let product = shenruGetProductDetail();
    console.log(product);

    const url = 'https://item.publish.taobao.com/sell/publish.htm?catId=' + product.catid + "&itemid=" + product.itemid;

    let features = "width=500,height=300";
    if (window.shenruDEBUG) {
        features = null;
    }
    let openWindow = window.open(url, "pushWindow", features);
    const result = await shenruPostMessage(openWindow, product, "https://item.publish.taobao.com");
    if (result["success"]) {
        openWindow.close();
    }
    console.log(result);
}

/**
 * 发布页面
 */
function shenruPagePublishInitView() {
    shenruPageInitCss();
    let containerView = document.createElement("div");
    containerView.id = "____"
    containerView.style = "display:block;position:fixed;z-index:999999;left:0;top:0;width:500px; height:280px"
    containerView.className = "srDialog"
    // containerView.style.transform = "translateX(100px)translateY(100px)";
    containerView.innerHTML = '<div  class="srList"> ' +
        '<div class="srListItem"><textarea id="__editView__" rows="2" cols="33" style="background-color: rgb(50,200,100);"></textarea></div>' +
        '<div class="srListItem"><span>价格设置:</span><span>乘以<input id="shernuPriceMul" type="text" style="width:40px" value="1.0"/></span><span>加上<input id="shernuPriceAdd" type="text" maxlength="8" style="width:40px" value="5"/></span></div>' +
        '<div class="srListItem"><span>价格类型:</span><span><input type="radio" name="priceType" value="original" checked>原价</span><span><input type="radio" name="priceType" value="promo" >活动价</span></div>' +
        '<div class="srListItem"><span>宝贝类型:</span><span><input type="radio" name="stuffStatus" value="new" checked>全新</span><span><input type="radio" name="stuffStatus" value="used" >二手</span></div>' +
        '<div class="srListItem"><button id="__publishView__">发布</button><button id="__testView__" style="margin-left:5px;">编辑</button><button id="__saveView__">保存</button></div>' +
        '<div class="srListItem"><span id="__progressView__"></span></div>' +
        '</div>';
    document.body.appendChild(containerView);


    let editView = containerView.querySelector("#__editView__");
    let saveView = containerView.querySelector("#__saveView__");
    let publishView = containerView.querySelector("#__publishView__");
    let progressView = containerView.querySelector("#__progressView__");
    let testView = containerView.querySelector("#__testView__");


    // publishView.style.display = "none";
    editView.style.display = "none";
    saveView.style.display = "none";

    publishView.addEventListener("click", function () {
        let data = window.__data__;
        let config = shenruPagePublishConfig(containerView);
        let pushData = Object.assign(config, data);
        // console.log(pushData);
        shenruPush(pushData);
    });

    saveView.addEventListener("click", function () {
        const storageKey = '_taobaodata_' + shenruGetUrlParameter("itemid");
        localStorage.setItem(storageKey, editView.value);
        shenruClipboard(editView.value);
        editView.style.display = "none";
        saveView.style.display = "none";
    });

    testView.addEventListener("click", function () {
        const storageKey = '_taobaodata_' + shenruGetUrlParameter("itemid");
        editView.value = localStorage.getItem(storageKey);
        shenruClipboard(editView.value);
        editView.style.display = "block";
        saveView.style.display = "block";
    });

    document.addEventListener('shenruLog', function (e) {
        // console.log(e);
        if (e.data && e.data.indexOf("progress:") === 0) {
            progressView.innerHTML = e.data.replace("progress:", "")
        }
    }, false);
}

/**
 * 获取配置页面数据
 * @param {*} containerView
 */
function shenruPagePublishConfig(containerView) {
    const priceTypeView = containerView.querySelector("input[name='priceType']:checked");
    const stuffStatusView = containerView.querySelector("input[name='stuffStatus']:checked");

    const priceMul = containerView.querySelector("#shernuPriceMul").value;
    const priceAdd = containerView.querySelector("#shernuPriceAdd").value;

    let priceStatus;
    if (priceTypeView) {
        priceStatus = priceTypeView.value;
    }
    let stuffStatus = null;
    if (stuffStatusView) {
        stuffStatus = stuffStatusView.value;
    }
    return {
        "shenruConfig": {
            "StuffStatus": stuffStatus,
            "priceType": priceStatus,
            "priceModify": {
                "priceMul": priceMul,
                "priceAdd": priceAdd,
            }
        }
    };
}

//==============================================================================================
// 商品详情
//==============================================================================================


/**
 *
 * 获取描述
 */
function shenruGetDesc() {
    return document.getElementById('J_DivItemDesc').innerHTML
}

// 获取商品属性
function shenruTaobaoGetSaleProp() {
    function getDataProperty(view) {
        if (view) {
            var result = [];
            for (var li of view.children) {
                let value = li.getAttribute('data-value');
                let aView = li.firstElementChild;
                let image = aView.style.background
                let text = aView.firstElementChild.innerText;
                //console.log(value, image, text);
                result.push({
                    value: value,
                    text: text,
                    image: image
                });
            }
            return result;
        }
    }

    var saleProp = {};

    var skinView = document.querySelector(".tb-skin");
    var salePropViews = skinView.querySelectorAll(".J_TSaleProp");
    for (var salePropView of salePropViews) {
        var text = salePropView.getAttribute("data-property");
        saleProp[text] = getDataProperty(salePropView);
    }
    return saleProp;
}

function shenruCatProp() {
    // <div id="attributes">
    //     <ul class="attributes-list">
    //         <li title="棉氨">面料材质:&nbsp;棉氨</li>
    //     </ul>
    // </div>
    let result = {};
    let attrView = document.getElementById("attributes");
    var attrListView = attrView.getElementsByClassName("attributes-list")[0];
    if (attrListView) {
        for (let i = 0; i < attrListView.children.length; i++) {
            var itemView = attrListView.children[i];
            //console.log(itemView.innerText);
            let attrs = itemView.innerText.split(": ");
            result[attrs[0]] = {
                text: attrs[1],
            };
        }
    }

    return result;
}


function shenruGetExtraData() {
    // let text = document.getElementsByClassName('J_Cont')[0].innerText
    // return '7天无理由' === text ? 1 : 0
    let result = [];
    let extraView = document.getElementById('J_tbExtra');
    for (let item of extraView.children) {
        let contentList = item.innerText.split('\n');
        result.push(contentList)
    }
    return result;
}

/**
 * 商品详情:获取标题
 * @returns {string}
 */
function shenruGetTitile() {
    // <h3 className="tb-main-title" data-title="短裤男潮牌夏季运动五分裤七分休闲中裤子男士宽松粉色沙滩大裤衩"
    //     data-spm-anchor-id="2013.1.iteminfo.i0.38eb432bNLxc2j">
    //   短裤男潮牌夏季运动五分裤七分休闲中裤子男士宽松粉色沙滩大裤衩
    // </h3>
    // return document.getElementsByClassName('tb-main-title')[0].innerText
    return document.getElementsByClassName('tb-main-title')[0].getAttribute('data-title')
}

/**
 * 商品详情: 宝贝类型
 */
function shenruGetStuffStatus() {
    let element = document.getElementsByClassName('tb-brand-title');
    if (element.length !== 0 && element[0].innerText.indexOf('二手') != -1) {
        return {
            'value': 6,
            'text': '二手'
        }
    } else {
        return {
            'value': 5,
            'text': '全新'
        }
    }
}

// TODO 未实现
function shenruGetDescType() {
    return {
        value: 0
    }
}

// TODO 作用未知
function shenruGetSellPromise() {
    let result = []
    return result.push({
        value: 1
    })
}

// 立即上架
function shenruGetStartTime() {
    return {
        type: 0
    }
}

function shenruGetVideo() {
    return []
}

function shenruGetSubStock() {
    return {
        value: 1
    }
}


function shenruWirelessDescType() {
    return {
        value: 1
    }
}

// TODO 未实现
function shenruGlobalStock() {
    return {
        'value': 'globalStock_0'
    }
}

// TODO 未实现
function shenruPaymentMode() {
    return {
        'value': 'buyNow'
    }
}

// 提价实现
function shenruImageVideo() {
    return null
}

function shenruImageVideoType() {
    return {
        value: 0
    }
}

function shenruSaleProp() {
    //
    // <div class="tb-skin">
    //     <ul data-property="颜色">
    //         <li data-value="1627207:6488472488">
    //             <a style="background:url(//gd2.alicdn.com/imgextra/i1/355047547/O1CN01QILhAT25cZgPNWVXn_!!355047547.jpg_30x30.jpg)">
    //                 <span>酒红色</span>
    //             </a>
    //         </li>
    //     </ul>
    // </div>
    var skinView = document.getElementsByClassName("tb-skin")[0];
    const ulViews = skinView.getElementsByTagName('ul');
    for (let ulView of ulViews) {
        if (ulView.hasAttribute("data-property")) {


            var dataProperty = ulView.getAttribute("data-property");

            let liViews = ulView.getElementsByTagName('li');
            for (let liView of liViews) {
                let aView = liView.getElementsByTagName('a')[0];
                let spanView = liView.getElementsByTagName('span')[0];
                var image = aView.style.getPropertyValue('background-image');
                console.log("i:", image, spanView.innerText);
            }
        }
    }
}


// TODO 未实现
function shenruGetSizeTemplate() {

}

/**
 * 获取数量
 * 数量有两种模式:
 * 1. 累计skuStrock
 * 2. 直接获取
 * @param sku
 * @returns {number}
 */
function shenruGetQuantity(sku) {
    //
    let result = 0
    if (sku) {
        for (let item of sku) {
            result += Number.parseInt(item.skuStock)
        }
    } else {
        result = document.querySelector('#J_SpanStock').innerText
    }
    return result
}

// https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId=538421815401&sellerId=825270931&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,upp,activity,fqg,zjys,amountRestriction,couponActivity,soldQuantity,page,originalPrice,tradeContract&callback=onSibRequestSuccess
function shenruGetPrice() {
    // <em className="tb-rmb-num">72.00-117.00</em>
    // window.g_config.price
    return document.getElementsByClassName('tb-rmb-num')[0].innerText
}

function shenruGetOriginalPrice() {
    // {
    //   ";20509:1961433971;1627207:1614547640;": {
    //      "price": "39.00"
    //   },
    //   "def": {
    //     "price": "39.00-48.00"
    //   }
    // }

    return window.g_config.originalPrice;
}

function shenruGetPromoPrice() {
    if (window.g_config.promotion) {
        return window.g_config.promotion.promoData;
    }
    return null;
}

function shenruGetActivityPrice() {
    // {
    //   "20509:1961433971;1627207:1860756925": "14.60",
    //   "def": "14.60"
    // }
    if (window.g_config.activity) {
        return window.g_config.activity.price;
    }
    return null;
}

function shenruGetImages() {
    let result = []
    const gallery = document.querySelectorAll('#J_UlThumb > li[data-index] * > img')
    for (let img of gallery) {
        result.push(img.src)
    }
    return result
}

/**
 * 获取 catId
 */
function shenruTaobaoGetCatId() {
    return g_config.idata.item.cid;
}

function shenruTaobaoGetItemId() {
    return shenruGetUrlParameter("id");
}

// 获取物流信息
function shenruTaobaoGetTbExtractWay() {
    const from = window.g_config.deliveryFee.data.sendCity;
    var servicelist = [];
    var serviceInfo = null;
    if (window.g_config.deliveryFee.data.serviceInfo.sku) {
        serviceInfo = window.g_config.deliveryFee.data.serviceInfo.sku["default"];
    } else {
        serviceInfo = window.g_config.deliveryFee.data.serviceInfo.list;
    }
    for (var item of serviceInfo) {
        var view = document.createElement("div");
        view.innerHTML = item.info
        console.log(view.innerText);
        servicelist.push(view.innerText);
    }

    var result = {};
    result["sendCity"] = from;
    result["servicelist"] = servicelist;

    return result;
}

function shenruGetProductDetail() {
    // window.Json.components.ifdWarning.props.icmp.global
    // "userId": 417990047,
    // "catId": 3035,
    // "id": 600489372886,
    //
    let auctionType = 'b'
    //
    let sevenDayDefaultValue = 1
    //
    let location = null
    //
    let taobaoMarketTransform = null
    //
    let taobaoMarketClean = null
    //
    let commitType = null
    //
    let snapshotId = null
    //
    let showDraft = 1
    //
    let dbDraftId = null
    //
    let xiaoxin = null
    //
    let skyLightRule = null
    //
    let foodSecuritySubmit = null
    //
    let ifdWarningSubmit = false
    //
    let fakeCreditSubmit = false
    //
    // 宝贝类型
    let stuffStatus = shenruGetStuffStatus()
    // 标题
    let title = shenruGetTitile()
    // 价格
    let price = shenruGetPrice()
    // 原价
    let originalPrice = shenruGetOriginalPrice()
    // 活动价
    let promoPrice = shenruGetPromoPrice()
    //
    let activityPrice = shenruGetActivityPrice()
    // 类目属性
    let catProp = shenruCatProp()
    //
    let descType = shenruGetDescType()
    //
    let desc = shenruGetDesc()
    //
    let sellPromise = shenruGetSellPromise()
    //
    let extraData = shenruGetExtraData()
    //
    let startTime = shenruGetStartTime()
    //
    let video = shenruGetVideo()
    //
    let subStock = shenruGetSubStock()
    //
    let wirelessDescType = shenruWirelessDescType()
    //
    let globalStock = shenruGlobalStock()
    //
    let paymentMode = shenruPaymentMode()
    //
    let imageVideo = shenruImageVideo()
    //
    let imageVideoType = shenruImageVideoType()
    //
    let saleProp = shenruTaobaoGetSaleProp()
    //
    let sizeTemplate = shenruGetSizeTemplate()

    //
    let images = shenruGetImages()

    //
    let sku = window.g_config.dynStock.sku; //shenruGetSku(saleProp)
    // 要做sku后面
    let quantity = shenruGetQuantity()
    // 物流
    let tbExtractWay = shenruTaobaoGetTbExtractWay()

    let result = {
        'catid': shenruTaobaoGetCatId(),
        'itemid': shenruTaobaoGetItemId(),
        'auctionType': auctionType,
        'sevenDayDefaultValue': sevenDayDefaultValue,
        'location': location,
        'taobaoMarketTransform': taobaoMarketTransform,
        'taobaoMarketClean': taobaoMarketClean,
        'commitType': commitType,
        'snapshotId': snapshotId,
        'showDraft': showDraft,
        'dbDraftId': dbDraftId,
        'xiaoxin': xiaoxin,
        'skyLightRule': skyLightRule,
        'foodSecuritySubmit': foodSecuritySubmit,
        'ifdWarningSubmit': ifdWarningSubmit,
        'fakeCreditSubmit': fakeCreditSubmit,
        'stuffStatus': stuffStatus,
        'sku': sku,
        'shopcat': [], //TODO 作用未知
        'descType': descType,
        'desc': desc,
        'sellPromise': sellPromise,
        'sevenDaySupport': null,  //extra 获取
        'extraData': extraData,
        'startTime': startTime,
        'video': video,
        'subStock': subStock,
        'wirelessDescType': wirelessDescType,
        'globalStock': globalStock,
        'paymentMode': paymentMode,
        'imageVideo': imageVideo,
        'imageVideoType': imageVideoType,
        'saleProp': saleProp,
        'sizeTemplate': sizeTemplate,
        'catProp': catProp,
        'quantity': quantity,
        'title': title,
        'price': price,
        'originalPrice': originalPrice,
        'promoPrice': promoPrice,
        'activityPrice': activityPrice,
        'images': images,
        'tbExtractWay': tbExtractWay
    }
    return result
}

/**
 * is upShelf
 */
function shenruGetIsUpShelf() {
    const offSaleView = document.querySelector('#detail  div.J_TOffSale strong')
    if (offSaleView) {
        return offSaleView.innerText === '此宝贝已下架'
    }
    return false
}

//==============================================================================================
// Publish
//==============================================================================================

async function shenruTaobaoCartPropDataSource(data, text) {
    // console.log(data);
    function equals(src, desc) {
        if (src === desc) {
            return true;
        }
        //
        const regex = /[\/]|[\.]/g;
        if (src.match(regex) && src.match(text)) {
            return true;
        }
        return false;
    }

    function findList(name, list, text) {
        let result;
        if (list) {
            for (let item of list) {
                if (equals(item.text, text)) {
                    result = {};
                    result[name] = {
                        "text": text,
                        "value": item.value
                    };
                    return result;
                }
            }
        }
        if (name === "p-20021") {
            // 材质兼容以前产品
            //https://item.taobao.com/item.htm?id=601554845953
            result = {};
            result[name] = list[0];
        } else {
            result = {};
            result[name] = {
                "text": text,
                "value": -1
            };
        }
        return result;
    }

    var result = null;
    if (data.uiType === "select" || data.uiType === "combobox") {
        result = findList(data.name, data.dataSource, text);
        if (result) {
            return result;
        }
        if (data.showSearch) {
            //data.async.childrenUrl  data.async.searchUrl
            var urlPath = data.async.searchUrl ? data.async.searchUrl : data.async.childrenUrl;
            var url = "https://item.publish.taobao.com/sell/" + urlPath;
            let sendData = 'keyword=' + encodeURIComponent(text)
                + '&pid=' + encodeURIComponent(data["name"])
                + '&queryType=' + encodeURIComponent("query");

            let responseStr = await shenruTaobaoRequest(url, 'POST', sendData);
            let response = JSON.parse(responseStr);
            if (response.success) {
                result = findList(data.name, response.data.dataSource, text);
                if (result) {
                    return result;
                }
            }
        }
    } else if (data.uiType === "material") {
        if (data.dataSource) {
            result = findList(data.name, data.dataSource, text);
            if (result) {
                return result;
            }
        }

        result = {};
        result[data.name] = [];
        // text = 棉65% 聚酯纤维31% 聚氨酯弹性纤维(氨纶)4%
        let textList = text.split(' ')
        for (let textItem of textList) {
            let textItemSplit = /(\W+)(\d+)/.exec(textItem)

            if (textItemSplit.length === 2) {
                result[data.name].push({
                    value: textItemSplit[1],
                    text: textItemSplit[1]
                });
            } else if (textItemSplit.length === 3) {
                result[data.name].push({
                    value: textItemSplit[1],
                    text: textItemSplit[1],
                    content: textItemSplit[2]
                });
            }
        }
        return result;
    } else if (data.uiType === "taoSirProp") {
        var result = {};
        result[data.name] = text;
        return result;
    } else if (data.uiType === "checkbox") {
        var result = {};
        result[data.name] = [];
        let textItemList = text.split(" ");
        for (let textItem of textItemList) {
            var find = findList(data.name, data.dataSource, textItem);
            result[data.name].push(find[data.name]);
            // for(let dataItem of data.dataSource){
            //     if(dataItem.text === textItem){
            //         result[data.name].push({
            //             "text": dataItem.text,
            //             "value": dataItem.value
            //         });
            //         break;
            //     }
            // }
        }
        return result;
    } else if (data.uiType === "input") {
        var result = {};
        result[data.name] = text;
        return result;
    } else if (data.uiType === "datepicker") {
        var result = {};
        result[data.name] = text;
        return result;
    }
    return null;
}


async function shenruTaobaoCartProp() {
    let catProp = window.__data__.catProp;

    var data = window.__data__;
    var catid = data["catid"];
    var url = "https://item.publish.taobao.com/sell/asyncOpt.htm?optType=taobaoCatProp&catId=" + catid + "&requiredKey=title-foodPrdLicense";
    var responseData = await shenruTaobaoRequest(url, "POST");
    responseData = JSON.parse(responseData);


    // let dataSourceList = window.Json.components.catProp.props.dataSource;
    let dataSourceList = responseData.models.catProp.dataSource;
    //"asyncOpt.htm?optType=taobaoBrandQuery&queryType=query&catId=121394006"
    //https://item.publish.taobao.com/sell/asyncOpt.htm?optType=taobaoBrandQuery&queryType=query&catId=121394006
    //https://item.publish.taobao.com/sell/asyncOpt.htm?optType=taobaoBrandQuery&queryType=query&catId=121394006

    // console.log(catProp);
    // console.log(dataSourceList);
    var result = {};
    for (let cat in catProp) {
        for (let dataSource of dataSourceList) {
            // console.log(cat, data.label);
            if (dataSource.label === cat) {
                let item = await shenruTaobaoCartPropDataSource(dataSource, catProp[cat].text);
                if (!item) {
                    console.error(cat);
                }
                let keys = Object.keys(item);
                result[keys[0]] = item[keys[0]];
            }
        }
    }
    return result;
}


async function shenruTaobaoPushSaleProp() {
    let saleProp = window.__data__.saleProp;
    if (Object.keys(saleProp).length == 0) {
        //如果没有属性
        return null;
    }
    //let components = window.Json.components;
    //{value: "20518:28314", text: "S", image: ""}
    // "saleProp":{
    //     "尺寸":[
    //         {
    //             "value":"20518:28314",
    //             "text":"S",
    //             "image":""
    //         }
    //     ]
    // }

    // "saleProp": {
    //     "p-20518": {
    //       "selectedSizeGroupId": {
    //         "text": "中国码",
    //         "value": "27013-men_bottoms",
    //         "subName": "sizeGroup_27013-men_bottoms",
    //         "sizeGroupType": "men_bottoms"
    //       },
    //       "value": [
    //         {
    //           "value": 28314,
    //           "text": "S"
    //           "img":"https://img.alicdn.com/imgextra/i3/417990047/O1CN01SenhKU1CDZAJVflen_!!417990047.jpg"
    //         }
    //       ]
    //     }
    // }
    function sizePropGroup(objDataList, propObj) {
        let result = {};
        result["value"] = [];
        let sizeGroup = null;
        for (let objData of objDataList) {
            let value1 = objData.value.split(":")[0];
            let value2 = objData.value.split(":")[1];

            if (!sizeGroup) {
                for (let sizeGroupItem of propObj.props.subItems) {
                    if (sizeGroupItem.name !== "selectedSizeGroupId") {
                        for (let sizeGroupItemData of sizeGroupItem.dataSource) {
                            if (sizeGroupItemData.value == value2) {
                                sizeGroup = sizeGroupItem;
                                break;
                            }
                        }
                        if (sizeGroup) {
                            break;
                        }
                    }
                }
            }


            result["value"].push({
                value: value2,
                text: objData.text,
                img: objData.image
            })
        }

        if (sizeGroup) {
            for (let sizeGroupItemData of propObj.props.subItems[0].dataSource) {
                if (sizeGroupItemData.subName === sizeGroup.name) {
                    result["selectedSizeGroupId"] = sizeGroupItemData
                    break;
                }
            }
        } else {
            result["selectedSizeGroupId"] = propObj.props.subItems[0].dataSource[0];
        }
        return result;
    }

    async function colorCheckboxGroup(objDataList, propObj) {
        let result = [];
        for (let dataItem of objDataList) {
            let image = shenruImageUrl(dataItem.image);
            if (image) {
                let resultData = await shenruTaobaoPushImageGetBlobAndSend(image);
                if (resultData.success) {
                    image = resultData.object.url;
                } else {
                    image = null;
                    console.warn("colorCheckboxGroup文件上传失败:" + image)
                }
            }

            result.push({
                text: dataItem.text,
                value: dataItem.value.split(":")[1],
                img: image
            })
        }
        return result;
    }

    async function colorPropGroup(objDataList, propObj) {
        let result = [];
        for (let dataItem of objDataList) {
            var isFind = false;
            for (let dataSource of propObj.props.dataSource) {
                if (dataItem.value.split(":")[1] == dataSource.value) {
                    var image = shenruImageUrl(dataItem.image);
                    if (image) {
                        let resultData = await shenruTaobaoPushImageGetBlobAndSend(image)
                        if (resultData.success) {
                            image = resultData.object.url
                        }
                    }

                    result.push({
                        text: dataItem.text,
                        value: dataSource.value + "",
                        rgb: dataSource.rgb,
                        img: image
                    });
                    isFind = true;
                    break
                }
            }
            if (!isFind) {
                var image = shenruImageUrl(dataItem.image);
                if (image) {
                    let resultData = await shenruTaobaoPushImageGetBlobAndSend(image)
                    if (resultData.success) {
                        image = resultData.object.url;
                    }
                }
                result.push({
                    text: dataItem.text,
                    value: dataItem.value.split(":")[1],
                    img: image
                });
            }
        }
        return result;
    }

    function sequentialComboboxGroup(objDataList, propObj) {
        let result = [];
        for (let dataItem of objDataList) {
            result.push({
                text: dataItem.text,
                value: dataItem.value.split(":")[1]
            });
        }
        return result;
    }

    function sequentialCheckboxGroup(objDataList, propObj) {
        let result = [];
        for (let dataItem of objDataList) {
            result.push({
                text: dataItem.text,
                value: dataItem.value.split(":")[1]
            });
        }
        return result;
    }

    let result = {};
    for (let sale in saleProp) {
        let objItem = saleProp[sale][0];

        let value1 = objItem.value.split(":")[0];
        let value2 = objItem.value.split(":")[1];
        let componentProp = shenruGetArrayItem(window.Json.components.sku.props.dataSource, "label", sale);
        if (componentProp) {
            let key = componentProp.name;
            let propObj = window.Json.components[key];
            if (propObj.type === "sizePropGroup") { //"sequentialComboboxGroup"
                let salePropResultData = sizePropGroup(saleProp[sale], propObj);
                result[key] = salePropResultData;
            } else if (propObj.type === 'sequentialComboboxGroup') {
                let salePropResultData = sequentialComboboxGroup(saleProp[sale], propObj);
                result[key] = salePropResultData;
            } else if (propObj.type === "colorCheckboxGroup") { //"colorCheckboxGroup"
                let salePropResultData = await colorCheckboxGroup(saleProp[sale], propObj);
                result[key] = salePropResultData;
            } else if (propObj.type === "sequentialCheckboxGroup") {
                let salePropResultData = sequentialCheckboxGroup(saleProp[sale], propObj);
                result[key] = salePropResultData;
            } else if (propObj.type === "colorPropGroup") {
                let salePropResultData = await colorPropGroup(saleProp[sale], propObj);
                result[key] = salePropResultData;
            }
        }

    }
    return result;
}

function shenruTaobaoPushSku(saleProps) {

    if (!saleProps) {
        return null;
    }
    //g_config.dynStock.sku
    let components = window.Json.components;
    const data = window.__data__;
    const shenruConfig = data["shenruConfig"];
    const result = [];

    function getSkuNames(keysList, salePropKeys, index, name) {
        const key = salePropKeys[index];
        let values = saleProps[key];
        const isLastKey = key === salePropKeys[salePropKeys.length - 1];

        if (name == null) {
            name = "";
        }

        if (!Array.isArray(values)) {
            values = values["value"];
        }

        for (let i = 0; i < values.length; i++) {
            const _name = name + ";" + key.replace("p-", "") + ":" + values[i]["value"];
            if (isLastKey) {
                keysList.push(_name + ";");
            } else {
                getSkuNames(keysList, salePropKeys, index + 1, _name);
            }
        }
    }

    const salePropKeys = Object.keys(saleProps);
    const keysList = [];
    getSkuNames(keysList, salePropKeys, 0);


    for (const key of keysList) {
        const key2 = key.replace(/^;|;+$/g, "");

        const skuStock = data["sku"][key] != null ? data["sku"][key].stock : 0;
        let skuPrice = null;

        if (shenruConfig["priceType"] == "promo" && data["promoPrice"] && data["promoPrice"][key]) {
            //获取活动价格
            skuPrice = data["promoPrice"][key][0].price;
        } else {
            // 获取原始价格
            skuPrice = data["originalPrice"][key].price;
        }

        if (shenruConfig["priceModify"]) {
            if (shenruConfig["priceModify"]["priceMul"]) {
                var priceMul = shenruConfig["priceModify"]["priceMul"];
                if (!Number.isNaN(Number.parseFloat(priceMul))) {
                    skuPrice = skuPrice * Number.parseFloat(priceMul);
                }
            }

            if (shenruConfig["priceModify"]["priceAdd"]) {
                var priceAdd = shenruConfig["priceModify"]["priceAdd"];
                if (!Number.isNaN(Number.parseFloat(priceAdd))) {
                    skuPrice = skuPrice + Number.parseFloat(priceAdd);
                }
            }
        }


        var salePropKey = key2.replace(/;/g, "_").replace(/:/g, "-");

        var skuItem = {
            skuStock: skuStock,
            skuPrice: skuPrice + "",
            skuId: null,
            props: [],
            action: {
                selected: true
            },
            salePropKey: salePropKey,
            readonlyFields: []
        };

        //1627207:6354978499
        var key2Splits = key2.split(";");
        for (var keyValues of key2Splits) {
            //keyValues[0]=1627207
            //keyValues[1]=6354978499
            var keyValuesSplit = keyValues.split(":");
            var salePropName = "p-" + keyValuesSplit[0];
            var saleProp = saleProps[salePropName];
            if (!Array.isArray(saleProp)) {
                saleProp = saleProp.value;
            }
            for (var salePropItem of saleProp) {
                if (salePropItem.value == keyValuesSplit[1]) {
                    salePropItem["name"] = salePropName;
                    skuItem["props"].push(salePropItem);
                    break;
                }
            }
        }
        //  if(skuItem["props"].length < 2){
        //      //https://item.taobao.com/item.htm?id=610036235436

        //      //skuItem["props"].length % 2 == 0
        //      //https://item.taobao.com/item.htm?id=600406523661
        //      // throw new Exception("SKU中的销售属性值必须成对填写");
        //      console.warn("SKU中的销售属性值必须成对填写");
        //  }else{
        //      result.push(skuItem);
        //  }
        result.push(skuItem);
    }

    // console.log(result);
    return result;
}


//计算总数量
function shenruTaobaoPushQuantity(skuObj) {
    if (skuObj) {
        let result = 0;
        for (let sku of skuObj) {
            result += sku.skuStock;
        }
        return result;
    }
    const data = window.__data__;
    return data["quantity"];
}

// 处理上传图片
async function shenruTaobaoPushImageProcess() {
    let data = window.__data__;

    let imgList = []
    for (let i = 0; i < data.images.length; i++) {
        let url = shenruTaobaoPushGetRealUrl(data.images[i]);
        let resultData = await shenruTaobaoPushImageGetBlobAndSend(url);
        if (resultData.success) {
            shenruLog("info", "progress:上传图片...[{0}%]".format(50 + i));
            imgList.push({
                'id': resultData.object.fileId,
                'url': resultData.object.url,
                'name': resultData.object.fileName,
                'size': resultData.object.size,
                'pix': resultData.object.pix,
                'folderId': resultData.object.fileId
            });
        } else {
            // throw '上传文件失败'
            console.warn('上传文件失败');
            console.warn(resultData);
        }
    }
    return shenruTaobaoPushImageProcess2(imgList);
}


function shenruTaobaoPushImageProcess2(imgList) {
    let images = []
    var verticalImage = [];

    for (var img of imgList) {
        const widht = img.pix.split("x")[0]
        const height = img.pix.split("x")[1]
        const rate = widht / height;
        if (rate < 0.7 && rate > 0.6) {
            verticalImage[0] = img;
        }
    }
    images = imgList.filter(item => item != verticalImage[0]);
    return {"images": images, "verticalImage": verticalImage};
}

// async function shenruTaobaoPushImageUpdate(jsonObj) {
//     let jsonStr = JSON.stringify(jsonObj);
//     const r = /"([https:]*\/\/.*?(jpg|gif|webp).*?)"/g;
//     let array = jsonStr.match(r);
//
//     let mySet = new Set();
//     for (let item of array) {
//         item = item.replace('\"', "").replace('\\\\\\"', "").replace('\\"', "");
//         mySet.add(item);
//     }
//     for (let item of mySet) {
//         let resultData = await shenruTaobaoPushImageGetBlobAndSend(item);
//         if (!resultData.success) {
//             throw '上传文件失败:' + item + ",resultData:" + resultData;
//         }
//         jsonStr = jsonStr.replace(item, resultData)
//     }
//     return JSON.parse(jsonStr);
// }


async function shenruTaobaoPushDescProcess(view) {
    if (view == null) {
        let data = window.__data__;
        let desc = data.desc;
        view = document.createElement('div');
        view.innerHTML = desc
    }

    for (const children of view.children) {
        if (children.hasAttributes()) {
            for (const attrs of children.attributes) {
                if (attrs.value.match("img.alicdn.com") && attrs.value.match(/\.gif$|\.jpg$|\.png$/)) {
                    // console.log(children);
                    // console.log(attrs.value);
                    let resultData = await shenruTaobaoPushImageGetBlobAndSend(attrs.value);
                    if (resultData.success) {
                        attrs.value = resultData.object.url;
                    } else {
                        console.log("desc文件上传失败:" + attrs.value);
                        attrs.value = '';
                    }
                }
            }


        }

        if (children.children.length > 0) {
            await shenruTaobaoPushDescProcess(children);
        }
    }
    return view.innerHTML;
}


/**
 * 物流模板查询
 * @param data
 * @returns {Promise<*>}
 */
async function shenruTaobaoPushTbExtractWayQuery(data) {
    // const data = window.__data__;
    // 查找模板.这里没有处理分页
    const queryUrl = "https://item.publish.taobao.com/sell/asyncOpt.htm?optType=refreshTemplates";
    let sendData = 'catId=' + encodeURIComponent(data["catid"]);
    let responseData = await shenruTaobaoRequest(queryUrl, "POST", sendData);
    return responseData;
}

/**
 * 运费
 * @returns {Promise<*>}
 */
async function shenruTaobaoPushTbExtractWay() {
    //TODO 使用
    const data = window.__data__;

    const tbExtractWay = data["tbExtractWay"];
    //模板name
    const templateName = shenruLogisticsTemplateName(tbExtractWay);


    let templates = await shenruTaobaoPushTbExtractWayQuery(data);
    templates = JSON.parse(templates);
    if (!templates.success) {
        throw "物流模板获取失败"
    }

    for (const dataSource of templates.data.dataSource) {
        if (shenruStringEndsWith(dataSource.text, templateName)) {
            return {
                "templateName": dataSource.text,
                "value": ["2"],
                "template": dataSource.value
            };
        }
    }


    // function messageCallback(event) {
    //     console.log("shenruTaobaoPushTbExtractWay>>messageCallback:" + event);
    // }
    //
    // window.addEventListener('message', messageCallback);

    const url = "https://adpmanager.taobao.com/user/template_setting.htm?fromType=fromPublishGpfTaobao";
    //, "width=1,height=1"
    const openWindow = window.open(url, 'adpmanager', "width=500,height=300");
    let result = await shenruPostMessage(openWindow, data, "*");
    result = JSON.parse(result);
    if (result.success) {
        //返回物流编号
        console.log("openWindow.close>>");
        openWindow.close();
        return {
            "value": ["2"],
            "templateName": result.resultData.templateName,
            "template": result.resultData.templateId
        };
    }
    return null;
}


function shenruTaobaoPushStuffStatus() {
    var data = window.__data__;
    var shenruConfig = data["shenruConfig"];
    if (shenruConfig["stuffStatus"] == "used") {
        return {
            'value': 6,
            'text': '二手'
        }
    } else if (shenruConfig["stuffStatus"] == "new") {
        return {
            'value': 5,
            'text': '全新'
        }
    }
    return data["stuffStatus"];
}

function shernuTaobaoPushPrice(sku) {
    if (sku && sku.length > 0) {
        return sku[0].skuPrice;
    }
    const data = window.__data__;
    const priceSplit = data.price.split("-");
    return priceSplit[priceSplit.length - 1] + "";
}

function shenruPushInit() {
    const storageKey = '_taobaodata_' + shenruGetUrlParameter("itemid");
    let dataStr = localStorage.getItem(storageKey);
    window.__data__ = JSON.parse(dataStr);
    console.log(window.__data__);
}

async function shenruPush(data) {
    // console.log(data);
    window.__data__ = data;
    window.__data2__ = {};

    // return null;
    let result = shenruTaobaoPushCopyProp(data,
        'title',
        'price',
        'auctionType',
        'sevenDayDefaultValue',
        'location',
        'descType',
        'sellPromise',
        'sevenDaySupport',
        'startTime',
        'subStock',
        'wirelessDescType',
        'globalStock',
        'paymentMode',
        'imageVideo',
        'imageVideoType',
        'saleProp',
        'sizeTemplate',
        'catProp',
        'quantity',
        'video'
    );

    if (!data["shenruConfig"]) {
        data["shenruConfig"] = {};
    }

    try {
        await shenruTaobaoCreateImageFolder();
        shenruLog("info", "progress:初始化...[10%]");
        let stuffStatus = shenruTaobaoPushStuffStatus();
        let tbExtractWay = await shenruTaobaoPushTbExtractWay();
        let catProp = await shenruTaobaoCartProp();
        let saleProp = await shenruTaobaoPushSaleProp();
        // console.log(saleProp);
        let sku = shenruTaobaoPushSku(saleProp);
        let price = shernuTaobaoPushPrice(sku);
        let quantity = shenruTaobaoPushQuantity(sku);
        shenruLog("info", "progress:上传图片...[50%]");
        let imagesObj = await shenruTaobaoPushImageProcess();
        let desc = await shenruTaobaoPushDescProcess();

        result['stuffStatus'] = stuffStatus;
        result['price'] = price;
        result['catProp'] = catProp;
        result['saleProp'] = saleProp;
        result['sku'] = sku;
        result['quantity'] = quantity;
        result['images'] = imagesObj["images"];
        result['verticalImage'] = imagesObj["verticalImage"];
        result['desc'] = desc;
        result['tbExtractWay'] = tbExtractWay;
        console.log(result);

        shenruLog("info", "progress:发布商品...[90%]");
        // result = shenruTaobaoPushImageUpdate(result);
        let responseBean = await shenruTaobaoPushSend(result);
        responseBean = JSON.parse(responseBean);
        shenruTaobaoPushResult(responseBean);
        return responseBean;
    } catch (e) {
        shenruLog("info", "progress:失败[100%]");
        shenruLog("error", e);
    }
    return null;
}


function shenruTaobaoPushResult(responseObj) {
    console.log(responseObj);
    const itemId = window.__data__["itemid"];

    let resultType = null;
    try {
        resultType = responseObj.models.globalMessage.type;
    } catch (e) {
    }

    if (resultType === 'success') {
        let successUrl = responseObj.models.globalMessage.successUrl;
        let mySuccessUrl = new URL(successUrl, 'http://127.0.01');
        let primaryId = mySuccessUrl.searchParams.get('primaryId');
        shenruLog("info", "progress:发布成功[100%]");
        shenruLog("write", "itemId=" + itemId + ",primaryId=" + primaryId);
        let url = 'https://item.taobao.com/item.htm?id=' + primaryId;
        window.open(url);
    } else {
        shenruLog("info", "progress:发布失败[100%]");
        shenruLog("write", "itemId=" + itemId + ",response=" + JSON.stringify(responseObj));
        alert("发布失败");
    }
}

async function shenruTaobaoPushSend(data) {
    // let catId = (new URL(document.location)).searchParams.get("catId");
    let catId = window.Json.components.ifdWarning.props.icmp.global.catId;
    let itemId = window.Json.components.ifdWarning.props.icmp.global.id
    let jsonBody = JSON.stringify(data)

    let sendData = 'catId=' + encodeURIComponent(catId) + '&itemId=' + encodeURIComponent(itemId) + '&jsonBody=' + encodeURIComponent(jsonBody)
    let requestUrl = "https://item.publish.taobao.com/sell/submit.htm";
    let response = await shenruTaobaoRequest(requestUrl, "POST", sendData);
    return response;
}

function shenruTaobaoPushCopyProp(obj, ...props) {
    var result = {};
    for (var prop of props) {
        result[prop] = obj[prop];
    }
    return result;
}

function shenruTaobaoPushGetMeta(metaName) {
    const metas = document.getElementsByTagName('meta')

    for (let i = 0; i < metas.length; i++) {
        if (metas[i].getAttribute('name') === metaName) {
            return metas[i].getAttribute('content')
        }
    }
    return '';
}


function shenruTaobaoPushGetRealUrl(url) {
    //https://gd3.alicdn.com/imgextra/i3/275277574/O1CN01oxInIp25owNjLNwPF_!!0-item_pic.jpg_50x50.jpg_.webp
    // gd1.alicdn.com/imgextra/i1/417990047/O1CN019sXP7O1CDZCPE53xU_!!417990047.png_50x50.jpg_.webp
    return url.match(/(.*?(.jpg|.png))/)[0];
}


async function shenruTaobaoCreateImageFolder() {
    const data = window.__data__;
    const name = data.itemid + "_" + new Date().getTime();
    const _tb_token_ = shenruTaobaoPushCookieGet("_tb_token_");
    let url = "https://stream.taobao.com/api/create_folder.api?_input_charset=utf-8&_tb_token_={0}&parentFolderId=0&folderName={1}&appkey=tu&_input_charset=utf-8";
    url = url.format(_tb_token_, name);
    let resultData = await shenruTaobaoRequest(url, "GET", null);
    resultData = JSON.parse(resultData);
    if (resultData.success) {
        window.__data2__["folderId"] = resultData.object.folderId;
        return true;
    }
    return false;
}

async function shenruTaobaoPushImageGetBlobAndSend(url) {
    // let url = 'http://127.0.0.1:8000/aaa.png'

    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest()
        request.responseType = 'blob'
        //request.onload = () => resolve(await shenruPushSendImage(xhr.response));
        request.onload = async function () {
            if (request.status == 200) {
                let newVar = await shenruTaobaoPushImageSendRequest(request.response);
                resolve(newVar)
            } else {
                const data = {
                    success: false,
                    code: request.status,
                    message: '上传文件失败'
                };
                resolve(data)
            }
        };
        // request.onerror = () => reject(request.statusText)
        request.onerror = function () {
            const data = {
                success: false,
                code: 9999,
                message: '上传文件失败'
            };
            resolve(data)
        };
        request.open('GET', url, true);
        request.send(null)
    })
}

function shenruTaobaoPushImageSendRequest(imageData) {
    const formData = new FormData();
    formData.append('name', 'desc_16.jpg');
    formData.append('ua', '119#Ml8aWZxdMdu8OMMzPOEgoyUwcMWSXeFL5lZtW5qJo+U/BJPUIokuaYlBZlHdJI2/j2SvEOrVlBgR37+tMWG0WiebVTtKySN2m5izgvIvJb1WeBVS0u357U8v16KQICwEuFeqg7nTYnleziNcrCGZB2sK6+M7MCIsOqBPpDvzn1NYBfiSGYufidGTO8jF+U2V7AY4R81r3f3SBFuEA9qQYg/K8gqB/rJe9NcXbzrbnC38W8J7vh2LkW9beAuTe2wxBKvrq9OumV5D3v4u6auCLJ62koNC7Ks2AbfQOPxhj/O7M/ZQ46lHs0bXbKPKqSHkM8q9XQUao4GLXTYu8dbx0XLuiGoBk2ui48PoWzGZu/cz1qOItbCA2dBQC6+p7/0J6sSV+LETc3EJ4pcQsNBU/fVy42abQ26DPd3A5xjz7+x19CeJ2L1f1Wk6dWo16qTI2ZmnFAWSX1BFc5521R57MJeoc1HAzkjOEsItDlSnBZHQfGpYZyXI6k6qsYfDmZFvJ+ZY660jq9eyqforQRwcGzVdgb++PAXtbl1MsKCmqruN0S0GgygGIrA8RJBONt7Mfe8LoPg1ItN8aJEI4lPASaALRJVVNNFG9oHd8qQUJ0xy9xPreGqKpZ8FtgWnNXg89wAS8BIM3F889xwbflkLuWX8RJVVNEHM9oAzVSqmFAFN42Wl4lkLduI8RU6WNEHJM0AzRqSbzqT0FUpXgzyQM6ILfPEexzchhfDjS3eB/G+2QNfuOKIOMU51R2NfB+gV2fn5QSaNc0dvYBFPJ6Myu3lGsELZVlM5q28gP/gJ4ScMn7g+gkep/9QzHpukA8gs4Shx/SDSuMjnZOgJuKelzOrBEOgd+X/lfw7d1xTt4Lcpjf0CL6aSWa70PomJzSr08HQmC7zydcj0XLqXj1pfnRejqgomWHy3MT62I8svBPla3qHOhe9joRAGZDfxKJJK4v8NrZF6QijCG5mkTZUilQptyB03FffARuAlGpclOVRDm5gZwl4j7pka/n2Aimu6XCb9qiu0Rom9NEv1Hfj6mPb5ohAlXe+/ylBNkLWxVj8UGTNuOG3ohyYKd+vT+6NZdTYL9tX5OE87S+o9w7+WRUPq82VQ8apBJ766s8BYafep9ow5+nG8cECF0ZCa5RbZ80L5kQR0mhrfZYZq3VQJkwF6KenCSqTosYZlf8S+UvqhCcW0MlugYqP6BYUYX5bDoEXQdp+5witxiJx37MYj6e593TYRnD2gXrs9rSRJ1OR0EBWzhHiSOAwf/Rv6u2piGTNj1W/zQcp=')
    formData.append('file', imageData, 'desc_16.jpg');

    let folderId = 0;
    if (window.__data2__ && window.__data2__["folderId"]) {
        folderId = window.__data2__["folderId"];
    }

    let requestUrl = 'https://stream-upload.taobao.com/api/upload.api?appkey=tu&folderId={0}&watermark=false&_input_charset=utf-8';
    requestUrl = requestUrl.format(folderId);

    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest()
        // request.onload = () => resolve(request.responseText)
        request.onload = function () {
            resolve(JSON.parse(request.responseText))
        };
        // request.onerror = () => reject(request.statusText)
        request.onerror = function () {
            const data = {
                success: false,
                message: '上传文件失败'
            };
            reject(data)
        };
        request.open('POST', requestUrl, true);
        request.withCredentials = true;
        request.send(formData)
    })
}

// 获取cookie
function shenruTaobaoPushCookieGet(key, def) {
    var result = document.cookie.match(key + "=(.+?);")[1]
    if (result) {
        return result;
    }
    return def;
}

function shenruTaobaoPushWindowMessage() {
    async function messageCallback(e) {
        if (!e.origin.includes("item.taobao.com")) {
            console.warn("shenruTaobaoPushWindowMessage:" + e);
            return;
        }
        let request = null;
        try {
            request = JSON.parse(e.data);
        } catch (e) {
        }
        if (request && request.reqTag && request.data) {
            console.log("clientMessage>>messageCallback:" + e.data);
            const storageKey = '_taobaodata_' + request.data.itemid;
            localStorage.setItem(storageKey, JSON.stringify(request.data));
            document.addEventListener('shenruLog', function (e) {
                // console.log(e);
                if (e.data && e.data.indexOf("progress:发布成功[100%]") === 0) {
                    const submitResult = {
                        "code": "0",
                        "success": "true"
                    };
                    const data = {
                        reqTag: request.reqTag,
                        data: submitResult
                    };
                    console.log("shenruTaobaoPushWindowMessage>>postMessage:" + JSON.stringify(data));
                    e.source.postMessage(JSON.stringify(data), "*");
                }
            }, false);
        }
    };

    window.addEventListener('message', messageCallback);
}

// 初始化加载
function shenruTaobaoPushLoad() {
    console.log("shenruTaobaoPushLoad>> load");
    shenruTaobaoPushWindowMessage();
    shenruConnectWindowListener();
}


//==============================================================================================
// Logistics
//==============================================================================================

// 通过名称获取id
// 上海      1,310000,310100
function shenruLogisticsConvertAddress(dic, addressStr) {
    // var tdist = {
    //     1: ["中国", "0"],
    //     2: ["阿富汗", "0"],
    //     227: ["美国本土外小岛屿", "0"],
    //     228: ["美国", "0"],
    //     11e4: ["北京", "1"],
    //     110100: ["北京市", "110000"],
    //     110114: ["昌平区", "110100"],
    //     13e4: ["河北省", "1"],
    //     44e4: ["广东省", "1"],
    //     45e4: ["广西壮族自治区", "1"],
    //     65e4: ["新疆维吾尔自治区", "1"],
    //     81e4: ["香港特别行政区", "1"],
    //     130100: ["石家庄市", "130000"],
    //     440300: ["深圳市", "440000"],
    //     65e4: ["新疆维吾尔自治区", "1"]
    // }
    //获取自列表
    function getChildList(code) {
        var result = {};
        for (var key in dic) {
            if (dic[key][1] === code) {
                result[key] = dic[key];
            }
        }
        return result;
    }

    //在列表中找到key. 如果是nation则全匹配, 否则开始包含
    function getDicKey(dicList, str, isNation) {
        for (var key in dicList) {
            if (isNation) {
                if (dicList[key][0] === str) {
                    return key;
                }
            } else {
                if (dicList[key][0].indexOf(str) == 0) {
                    return key;
                }
            }
        }
        return null;
    }

    var result = [];
    // 获取国家列表
    var nationDic = getChildList("0");
    var findKey = getDicKey(nationDic, addressStr, true);
    if (findKey) {
        // 国际则直接返回
        result.push(findKey);
        return result;
    }

    if (result.length == 0) {
        // 不是国际默认添加中国
        result.push("1");
    }

    var findStr;
    // 省,市列表
    var provinceDic = getChildList(result[result.length - 1]);
    // 查找省. 词最少为两个字
    for (var i = 2; i <= addressStr.length; i++) {
        var sub = addressStr.substr(0, i);
        findKey = getDicKey(provinceDic, sub, false);
        if (findKey) {
            findStr = sub;
            result.push(findKey);
            break;
        }
    }
    // 查询市
    var countyDic = getChildList(result[result.length - 1]);
    if (Object.keys(countyDic).length == 1) {
        //如果只有一个市. 比如北京
        result.push(Object.keys(countyDic)[0]);
        countyDic = getChildList(result[result.length - 1]);
    }

    var sub = addressStr.substr(findStr.length, addressStr.length - 1)
    if (sub !== "") {
        findKey = getDicKey(countyDic, sub, false);
        result.push(findKey);
    }
    return result;
}

// 尝试获取本地字典字段
// tdist 本地字典
async function shenruLogisticsAddressDic(tbExtractWay) {
    let count = 0;
    return new Promise((resolve, reject) => {
        const intervalId = window.setInterval(() => {
            if (window["tdist"]) {
                window.clearInterval(intervalId);
                resolve(shenruLogisticsConvertAddress(window["tdist"], tbExtractWay["sendCity"]));
                return;
            }
            //尝试缓存
            if (count > 30) {
                window.clearInterval(intervalId);
                reject([]);
            }
            count++;
        }, 1000);
    });
}


/**
 * 生成模板名称.模板限制25位.
 * 国家(1中国,0其他)+宝贝地址+运费方式+价格(如果是免费则剩率). 去掉空格¥和小数0
 * @param {*} tbExtractWay
 */
function shenruLogisticsTemplateName(tbExtractWay, addressId) {
    //data:{"sendCity":"河北石家庄","servicelist":["快递 免运费↵"]}
    //河北石家庄快递
    //data:{"sendCity":"河北石家庄","servicelist":["快递 免运费↵", "↵EMS ¥30.00"]}
    //中国河北石家庄快递EMS30
    //data:{"sendCity":"河北石家庄","servicelist":["快递 ¥30.00↵", "↵EMS ¥30.00"]}
    //1河北石家庄快递30EMS30
    let nationCode = "";
    if (addressId) {
        nationCode = addressId[0]
    }

    let result = tbExtractWay["sendCity"];
    for (let item of tbExtractWay["servicelist"]) {
        result += item.replace(" ", "").replace("↵", "").replace("免运费", "").replace("¥", "").replace(".00", "");
    }
    return nationCode + result;
}

// 生成模板
function shenruLogisticsNormalTemplate(tbExtractWay) {
    var template = {
        "checkboxGroup": [],
        "title": "运送方式：",
        "tips": [
            "除指定地区外，其余地区的运费采用“默认运费”"
        ]
    };

    var list = [];
    list.push({"title": "快递", startFee: "0", "value": "-4", "checked": false})
    list.push({"title": "EMS", startFee: "0", "value": "-7", "checked": false})
    list.push({"title": "平邮", startFee: "0", "value": "-1", "checked": false})

    for (var listItem of list) {
        for (var servicelistItem of tbExtractWay["servicelist"]) {
            servicelistItem = servicelistItem.replace("↵", "").replace("¥", "").replace("免运费", "0");
            if (listItem["title"] === servicelistItem.split(' ')[0]) {
                listItem["startFee"] = servicelistItem.split(' ')[1];
                listItem["checked"] = true;
            }
        }
    }

    for (var item of list) {
        var title = item["title"];                      //快递名称
        var value = item["value"];                      //快递value, 暂时未知
        var checked = item["checked"];                  //是否开启
        var startFee = checked ? item["startFee"] : ""; //标准运费
        var addFee = checked ? "0" : "";                //增加运费
        template["checkboxGroup"].push({
            "template": {
                "defaultConfig": [
                    {
                        "name": "startStandard",
                        "addonAfter": "{unit}内",
                        "value": "1"
                    },
                    {
                        "name": "startFee",
                        "addonAfter": "元，",
                        "value": startFee
                    },
                    {
                        "name": "addStandard",
                        "label": "每增加",
                        "addonAfter": "{unit}，",
                        "value": "1"
                    },
                    {
                        "name": "addFee",
                        "label": "增加运费",
                        "addonAfter": "元",
                        "value": addFee
                    }
                ],
                "title": "默认运费"
            },
            "defaultFee": false,
            "checked": checked,
            "disabled": false,
            "title": title,
            "value": value
        });
    }
    return template;
}


/**
 * @ return
 * code:0, message:"", data
 */

//{"redirect":"https://adpmanager.taobao.com/user/template_list.htm?fromType=fromPublishGpfTaobao","resultData":{"templateId":26845890560},"success":true}
async function shenruLogisticsSubmit(data) {
    const tbExtractWay = data["tbExtractWay"];

    const addressId = await shenruLogisticsAddressDic(tbExtractWay);
    const templateName = shenruLogisticsTemplateName(tbExtractWay, addressId);

    let normalTemplate = shenruLogisticsNormalTemplate(tbExtractWay);
    let promotionTemplate = {
        "template": {},
        "checked": false,
        "title": "指定条件包邮",
        "value": "0",
        "tips": "<img src='//img.alicdn.com/tps/i1/TB1Sw5KFVXXXXb7XFXX1xhnFFXX-23-12.png'>可选"
    };

    let _tb_token_ = shenruTaobaoPushCookieGet("_tb_token_");
    const url = "https://adpmanager.taobao.com/user/template_setting.htm?/user/template_setting.htm=";

    let sendData = 'valuation=' + encodeURIComponent(0)
        + '&fromType=' + encodeURIComponent("fromPublishGpfTaobao")
        + '&templateName=' + encodeURIComponent(templateName)
        + '&event_submit_do_save_template=' + encodeURIComponent("1")
        + '&consignDate=' + encodeURIComponent("4")
        + '&addressId=' + encodeURIComponent(addressId.join())
        + '&bearFreight=' + encodeURIComponent("0")
        + '&action=' + encodeURIComponent("user/template_setting_action")
        + '&_tb_token_=' + encodeURIComponent(_tb_token_)
        + '&normalTemplate=' + encodeURIComponent(JSON.stringify(normalTemplate))
        + '&promotionTemplate=' + encodeURIComponent(JSON.stringify(promotionTemplate));
    let resultData = await shenruTaobaoRequest(url, "POST", sendData);
    //添加模板名称
    // resultData["templateName"] = templateName;
    resultData = JSON.parse(resultData);
    resultData["resultData"] = Object.assign(resultData["resultData"], {
        "templateName": templateName
    });
    return JSON.stringify(resultData);
}

async function shenruLogisticsProcess(data) {
    // await shenruLogisticsSubmit(JSON.parse(request.data));
    return await shenruLogisticsSubmit(data)
}

/**
 * 监听消息
 * data格式
 * {
        "sendCity":"上海",
        "servicelist":["快递 免运费↵", "↵EMS ¥30.00"]
    }
 */
function shenruLogisticsWindowMessage() {
    async function messageCallback(e) {
        var request = null;
        try {
            request = JSON.parse(e.data);
        } catch (e) {
        }
        if (request && request.reqTag && request.data) {
            console.log("clientMessage>>messageCallback:" + e.data);
            window.__messageData__ = e.data;
            const submitResult = await shenruLogisticsProcess(request.data);
            const data = {
                reqTag: request.reqTag,
                data: submitResult
            };
            console.log("shenruLogisticsWindowMessage>>postMessage:" + JSON.stringify(data));
            e.source.postMessage(JSON.stringify(data), "*");
        }
    }

    window.addEventListener('message', messageCallback);
}


// 初始化加载
function shenruLogisticsLoad() {
    console.log("shenruLogisticsLoad>> load");
    shenruLogisticsWindowMessage();
    shenruConnectWindowListener();
}


async function shenruTaobaoPushPromise() {
    return new Promise((resolve, reject) => {
        if (false) {
            resolve("ok")
        } else {
            reject(null);
        }
    });
}


//==============================================================================================
// SDK
//==============================================================================================
/**
 * sdk
 * @param {} text
 */
function shenruClipboard(text) {
    // data.items.add("text/plain", text);
    navigator.clipboard.writeText(text).then(function () {
        /* success */
        //   alert("复制成功");
    }, function () {
        /* failure */
        //alert("复制失败");
        console.e("复制失败");
    });
}

/**
 * 获取数组中Obj
 * @param array
 * @param objKey
 * @param content
 * @returns {null}
 */
function shenruGetArrayItem(array, objKey, content) {
    for (let item of array) {
        if (item[objKey] === content) {
            return item
        }
    }
    return null
}


//=============================================================================================================
// window postmessage lib


//server
//  postMessage("")
//client
// 1. server.postMessage(reqTag);
// 2. client.postMessage(reqTag);
// 3. server.setConnected();
//
// {reqTag:xxxx, WindowConnect:true}
// {reqTag:xxxx, WindowConnectOk:true}
//
// window.postMessage();
// window.isConnectPostMessage //是否已链接
// window.source

function shenruConnectWindowListener() {
    function messageCallback(e) {
        let request = null;
        try {
            request = JSON.parse(e.data);
        } catch (e) {
        }
        if (!!(request && request.reqTag && request.WindowConnect)) {
            // console.log("shenruConnectWindowListener>>messageCallback:" + e.data);
            const data = {
                reqTag: request.reqTag,
                WindowConnectOk: true
            };
            window.removeEventListener('message', messageCallback);
            console.log("shenruConnectWindowListener>>postMessage:" + JSON.stringify(data));
            e.source.postMessage(JSON.stringify(data), "*");
        }
    }

    window.addEventListener('message', messageCallback);
}

async function shenruConnectWindow(openWindow, targetOrigin) {
    var reqTag = shenruUuid();
    var count = 0;
    var intervalId;


    return new Promise((resolve, reject) => {
        if (openWindow.isConnectPostMessage) {
            //connect callback
            resolve(true);
        } else {
            // wait responst
            function messageCallback(e) {

                console.log(this);
                var responst = null;
                try {
                    responst = JSON.parse(e.data);
                } catch (e) {

                }
                if (responst && responst.reqTag === reqTag) {
                    // callback success
                    console.log("shenruConnectWindow>>messageCallback:" + e.data);
                    window.removeEventListener('message', messageCallback);
                    window.clearInterval(intervalId);
                    if (responst.WindowConnectOk === true) {
                        window.isConnectPostMessage = true;
                        resolve(true);
                    } else {
                        window.isConnectPostMessage = false;
                        reject(false);
                    }
                }
            }

            window.addEventListener('message', messageCallback);

            intervalId = window.setInterval(function () {
                console.log("setInterval:" + count);
                if (count > 10) {
                    window.removeEventListener('message', messageCallback);
                    window.clearInterval(intervalId);
                    reject(false);
                    return;
                }
                count++
                var data = {
                    reqTag: reqTag,
                    WindowConnect: true
                }
                console.log("shenruConnectWindow>>window.windowId:" + window.windowId);
                console.log("shenruConnectWindow>>postMessage:" + JSON.stringify(data));
                openWindow.postMessage(JSON.stringify(data), targetOrigin);
            }, 2000);
        }
    });
}

// {reqTag:"xxxx"}
async function shenruPostMessage(openWindow, message, targetOrigin, timeout) {
    targetOrigin = targetOrigin ? targetOrigin : '*';
    timeout = timeout ? timeout : 3 * 60 * 1000;

    var isConnet = await shenruConnectWindow(openWindow, targetOrigin);
    var reqTag = shenruUuid();
    var timeoutId;
    return new Promise((resolve, reject) => {
        if (isConnet) {
            function messageCallback(e) {
                var responst = null;
                try {
                    responst = JSON.parse(e.data);
                } catch (e) {

                }
                if (responst && responst.reqTag === reqTag) {
                    console.log("shenruPostMessage>>messageCallback:" + e.data);
                    // callback success
                    window.removeEventListener('message', messageCallback);
                    window.clearTimeout(timeoutId);
                    resolve(responst.data);
                }
            }

            window.addEventListener('message', messageCallback);
            timeoutId = window.setTimeout(function () {
                window.removeEventListener('message', messageCallback);
                reject("");
            }, timeout);
            const data = {
                reqTag: reqTag,
                data: message
            };
            console.log("shenruPostMessage>>postMessage:" + JSON.stringify(data));
            openWindow.postMessage(JSON.stringify(data), targetOrigin);
        } else {
            reject("");
        }
    });
}

//========================================================================================================
// http 请求
//========================================================================================================
// 接口请求.成功返回数据,失败返回null
async function shenruTaobaoRequest(requestUrl, method, sendData) {
    let token = shenruTaobaoPushGetMeta('csrf-token');
    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.onload = function () {
            resolve(request.responseText)
        };
        request.onerror = function () {
            reject(null)
        };
        request.open(method, requestUrl);
        request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        request.setRequestHeader('Accept', 'application/json, text/plain, */*');
        request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        request.setRequestHeader('X-XSRF-TOKEN', token);
        request.withCredentials = true;
        request.send(sendData)
    })
}

async function shenruTaobaoRequest2(requestUrl, method, sendData) {
    let token = shenruTaobaoPushGetMeta('csrf-token')
    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest()
        request.onload = function () {
            const data = {
                success: true,
                data: request.responseText
            }
            resolve(data)
        }
        request.onerror = function () {
            const data = {
                success: false,
                message: '发送失败'
            }
            reject(data)
        }
        request.open(method, requestUrl)
        request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
        request.setRequestHeader('Accept', 'application/json, text/plain, */*')
        request.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        request.setRequestHeader('X-XSRF-TOKEN', token)
        request.withCredentials = true
        request.send(sendData)
    })
}


function shenruUuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}


function shenruGetUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}


/**
 * 处理各种img
 * @param {}} img
 */
function shenruImageUrl(url) {
    //
    if (!url) {
        return url;
    }

    //
    var regexp = /"(.*[\.png|\.jpg|\.gif])"/;
    var match = url.match(regexp);

    if (match) {
        return shenruGetRealUrl(match[1]);
    }
    return url;
}

function shenruGetRealUrl(url) {
    //https://gd3.alicdn.com/imgextra/i3/275277574/O1CN01oxInIp25owNjLNwPF_!!0-item_pic.jpg_50x50.jpg_.webp
    // gd1.alicdn.com/imgextra/i1/417990047/O1CN019sXP7O1CDZCPE53xU_!!417990047.png_50x50.jpg_.webp
    return url.match(/(.*?(.jpg|.png))/)[0];
}

/**
 * load js
 * @param url
 */
function shenruLoadJs(url) {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}


function shenruLoadCssCode(code) {
    const style = document.createElement('style');
    style.type = 'text/css';
    style.rel = 'stylesheet';
    //for Chrome Firefox Opera Safari
    style.appendChild(document.createTextNode(code));
    //for IE
    //style.styleSheet.cssText = code;
    const head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function (s, i) {
        return args[i];
    });
}

/**
 * 获取数组中Obj
 * @param array
 * @param objKey
 * @param content
 * @returns {null}
 */
function shenruGetArrayItem(array, objKey, content) {
    for (let item of array) {
        if (item[objKey] === content) {
            return item
        }
    }
    return null
}

/**
 * endsWith : Returns true if this string ends with the specified suffix.
 * @param src
 * @param content
 * @returns {boolean}
 */
function shenruStringEndsWith(src, content) {
    if (src == null || content == null) {
        return false;
    }
    const index = src.lastIndexOf(content);
    if (index === -1) {
        return false;
    }
    return (index + content.length) === src.length;
}


function shenruLog(tag, data) {
    const event = document.createEvent('Event');
    event.initEvent('shenruLog', true, true);
    event.tag = tag;
    event.data = data;
    document.dispatchEvent(event);

    if (tag === "info") {
        console.info(tag, data);
    } else if (tag === "write") {
        console.info(tag, data);
        _czc.push(["_trackEvent", tag, data]);
    } else if (tag !== null || tag === "error") {
        console.error(tag, data);
        _czc.push(["_trackEvent", tag, data]);
    }
}

window.shenruLog = shenruLog;

